<?php

/**
 * Created by PhpStorm.
 * User: GadflyBSD
 * Date: 16/3/14
 * Time: 16:30
 */
class BusinessModel extends PublicModel{
	public function getCategory($upid=0){
		$data = array();
		if($upid==0){
			foreach(M('WangkaCategory')->where('upid=0')->select() AS $val){
				foreach(M('WangkaCategory')->where('upid='.$val['id'])->select() AS $v){
					$data[] = array(
						'id'    => $v['id'],
						'title' => $v['title'],
						'main'  => $val['title'],
						'url'   => U('Business/shopList', array('cid' => $v['id'])),
					);
				}
			}
		}else{
			$val = M('WangkaCategory')->where('id='.$upid)->find();
			foreach(M('WangkaCategory')->where('upid='.$upid)->select() AS $v){
				$data[] = array(
					'id'    => $v['id'],
					'title' => $v['title'],
					'main'  => $val['title'],
					'url'   => U('Business/shopList', array('cid' => $v['id'])),
				);
			}
		}

		return array('errcode' => 0, 'data' => $data);
	}

	/**
	 * 创建商铺模型
	 * @return array
	 */
	public function createShop($post){
		$wx = session('wkshop');
		if($wx['sideInfo']['isbind'] != 0)
			return array('errcode' => "30101");     //您已经创建过商铺或者绑定过商铺,请不要重复创建商铺!
		if(!$this->validator('require', $post['title']))
			return array('errcode' => '30102');     //商铺名称输入有误！商铺名称必须输入！
		if(!$this->validator('unique', $post['title'], array('table' => 'WangkaShop', 'field' => 'title')))
			return array('errcode' => '30103');
		if($post['bossPassword'] == $post['personPassword'])
			return array('errcode' => '30104');     //安全起见，员工密码不能和老板密码一样！
		if(!$this->validator('require', $post['bossPassword']))
			return array('errcode' => '30105');     //老板密码不能为空或者老板密码格式不正确！
		if(!$this->validator('require', $post['personPassword']))
			return array('errcode' => '30106');     //员工密码不能为空或者员工密码格式不正确！
		Vendor('ChinaPnr');
		$pnr = new ChinaPnr('finance');
		$data = array(
			'user_name'     => $post['user_name'],
			'cert_id'       => $post['cert_id'],
			'user_mobile'   => $post['user_mobile'],
			'sms_code'      => $post['sms_code'],
			'sms_order_date'=> date('Ymd'),
			'sms_order_id'  => $post['sms_order_id'],
		    'mer_priv'      => array('sid' => $wx['sideInfo']['sid'], 'uid' => $wx['sideInfo']['uid']),
		);
		$result = $pnr->openAccount($data);
		if($result['errcode'] == '101000'){
			$halt = randstr();
			$state = $this->getCache('dealType_shopRegister');
			$auto = array(
				'uid'               => $wx['sideInfo']['uid'],
				'boss_password'     => md5(md5($post['bossPassword']).$halt),
				'preson_password'   => md5(md5($post['personPassword']).$halt),
				'halt'              => $halt,
				'role'              => 'boss',
				'cid'               => $post['cid']['id'],
				'user_cust_id'      => $result['data']['user_cust_id'],
				'acct_id'           => $result['data']['acct_id'],
				'last_changes'      => 'shopRegister',
				'last_unite'        => $state['id'],
				'last_recip'        => get_client_ip(),
				'last_remark'       => $post['user_mobile'],
			);
			$add = $this->curd(array('type' => 'add', 'model' => M('WangkaShop'), 'data' => array_merge($post, $auto)));
			if($add['errcode'] == '0'){
				D('Public')->getSession(true);
				$message = '您已经成功创建商铺, 您的微信号也同时绑定成该商铺的老板账户,您可以通过微信管理您的员工, 创建订单和查账！【此提醒来自汪卡技术团队】';
				$pushmsg = D('Pushmsg')->createShop(array(
					'openid'    => $wx['sideInfo']['openid'],
					'title'     => $post['title'],
					'category'  => M('WangkaCategory')->where('id='.$post['cid'])->getField('title'),
					'mobile'    => $post['mobile'],
					'password'  => $post['personPassword'],
				));
				if($pushmsg['errcode'] == '0')
					return array('errcode' => '0', 'content' => $message);
				else
					return $pushmsg;
			}else{
				return $add;
			}
		}else{
			return $result;
		}
	}

	public function bindPerson($post){
		$wx = session('wkshop');
		if($wx['sideInfo']['isbind'] != 0)
			return array('errcode' => '30101');
		if(!$this->validator('require', $post['sid']))
			return array('errcode' => '30107');
		if(!$this->validator('number', $post['sid']))
			return array('errcode' => '30108');
		$shop = M('WangkaShop')->where('sid='.$post['sid'])->field('uid, title, preson_password, halt')->find();
		if($shop['preson_password'] == md5(md5($post['password']).$shop['halt'])){
			$state = $this->getCache('dealType_bindPerson');
			$data = array(
				'last_uid'      => $wx['sideInfo']['uid'],
				'last_remark'   => $post['mobile'],
				'last_recip'    => get_client_ip(),
				'last_changes'  => 'bindPerson',
				'last_unite'    => $state['id'],
			);
			$save = $this->curd(array('type' => 'save', 'model' => M('WangkaShop'), 'data' => $data, 'where' => 'sid='.$post['sid']));
			if($save['errcode'] == 0){
				$wx = D('Public')->getSession(true);
				$content = '您已经成功成为商铺【'.$post['title'].'】的员工,请您通知您的老板为您配置操作权限!';
				$message = '员工管理提醒：有一个新员工【'.$post['mobile'].'】加入到您的商铺。祝您生意兴隆，万事如意！！！【此提醒来自汪卡技术团队】';
				$pushmsg = D('Pushmsg')->message('WKSHOP', $wx['openid'], $content);
				if($pushmsg['errcode'] == 0){
					$pushmsg_boss = D('Pushmsg')->message('WKSHOP', $wx['sideInfo']['boss_openid'], $message);
					if($pushmsg_boss['errcode'] == 0){
						return array('errcode' => '0', 'content' => $content);
					}else{
						return $pushmsg_boss;
					}
				}else{
					return $pushmsg;
				}
			}else{
				return $save;
			}
		}else{
			return array('errcode' => '30109');
		}
	}

	public function bindBank($post){
		$wx = session('wkshop');
		$data = array(
			'sid'       => $wx['sideInfo']['sid'],
			'bank_id'   => $post['bank_id']['code'],
			'bank_name' => $post['bank_id']['lable'],
			'bank_user' => $post['user_name'],
			'bank_code' => $post['card_no'],
			'card_prov' => $post['card_prov']['prov'],
			'card_area' => $post['card_area']['area'],
		);
		$add = $this->curd(array('type' => 'add', 'model' => M('WangkaBank'), 'data' => $data));
		if($add['errcode'] == 0){
			Vendor('ChinaPnr');
			$pnr = new ChinaPnr('finance');
			$post = array(
				'user_cust_id'  => $wx['sideInfo']['user_cust_id'],
				'bank_id'       => $post['bank_id']['code'],
				'card_no'       => $post['card_no'],
				'dc_flag'       => 'D',
				'card_prov'     => $post['card_prov']['prov'],
				'card_area'     => $post['card_area']['area'],
				'is_default'    => '00000001',
				'mer_priv'      => json_encode_plus(array('sid' => $wx['sideInfo']['sid'], 'uid' => $wx['sideInfo']['uid'])),
			);
			return $pnr->withdrawBindCard($post);
		}else{
			return $add;
		}
	}

	public function userWithdraw($data){
		$resp = json_decode($data['mer_priv']);
		$unite = $this->getCache('dealType_withdrawComplete');
		$money = M('WangkaShop')->where('sid='.$resp['sid'])->field('freeze, withdraw_num, withdraw_total')->find();
		$data = array(
			'freeze'        => $money['freeze'] - $data['trans_amt'],
			'withdraw_num'  => $money['withdraw_num'] + 1,
			'withdraw_total'=> $money['withdraw_total'] + $data['trans_amt'],
			'last_changes'  => 'withdraw',
			'last_unite'    => $unite['id'],
			'last_remark'   => $data['trans_amt'],
		);
		M('WangkaShop')->where('sid='.$resp['sid'])->save($data);
	}

	/**
	 * 用户提现操作
	 * @param $post
	 *
	 * @return array
	 */
	public function withdraw($post){
		$shop = M('WangkaShop')->where('sid='.$post['sid'])->field('uid, title, boss_password, halt')->find();
		if($shop['boss_password'] == md5(md5($post['boss_password']).$shop['halt'])){
			Vendor('ChinaPnr');
			$pnr = new ChinaPnr();
			$wx = session('wkshop');
			$bank_code = M('WangkaBank')->where('sid='.$wx['sideInfo']['sid'])->getField('bank_code');
			$post = array(
				'user_cust_id'  => $wx['sideInfo']['user_cust_id'],
				'trans_amt'     => $post['trans_amt'].'.00',
				'card_no'       => $bank_code,
				'mer_priv'      => json_encode_plus(array('sid' => $wx['sideInfo']['sid'], 'uid' => $wx['sideInfo']['uid'])),
			);
			$withdraw = $pnr->withdraw($post);
			if($withdraw['errcode'] == '202002'){
				return $this->withdrawAccept($withdraw['data']);
			}else{
				$resp = json_decode($withdraw['data']['mer_priv'], true);
				$openid = M('WangkaBindView')->where('sid='.$resp['sid'])->limit(1)->getField('boss_openid');
				$message = '您有一笔提现失败啦, 原因是: '.urldecode($withdraw['data']['resp_desc']);
				$pushmsg = D('Pushmsg')->message('WKSHOP', $openid, $message);
				if($pushmsg['errcode'] == 0){
					return array('errcode' => $withdraw['errcode'], 'content' => $message);
				}else{
					return $pushmsg;
				}
			}
		}else{
			return array('errcode' => '30112');
		}
	}

	/**
	 * 提现已受理
	 * @param $data
	 *
	 * @return array
	 */
	private function withdrawAccept($data){
		$resp = json_decode($data['mer_priv']);
		$unite = $this->getCache('dealType_withdrawAccept');
		$money = M('WangkaShop')->where('sid='.$resp['sid'])->field('freeze, withdraw_num, withdraw_total')->find();
		$data = array(
			'freeze'        => $money['freeze'] + $data['trans_amt'],
			'withdraw'      => $money['withdraw'] - $data['trans_amt'],
			'last_changes'  => 'withdrawAccept',
			'last_unite'    => $unite['id'],
			'last_remark'   => $data['trans_amt'],
		);
		$save = $this->curd(array('type' => 'save', 'model' => M('WangkaShop'), 'where' => 'sid='.$resp['sid'], 'data' => $data));
		if($save['errcode'] == 0){
			$wx = session('wkshop');
			$message = '您有一笔提现已受理, 提现金额: ￥'.$data['trans_amt'].', 此笔提现将扣除手续费: ￥'.$data['fee_amt'].',实际到账金额为: ￥'.$data['real_trans_amt'].', 请耐心等待! ';
			$pushmsg = D('Pushmsg')->message('WKSHOP', $wx['sideInfo']['boss_openid'], $message);
			if($pushmsg['errcode'] == 0){
				return array('errcode' => '0', 'content' => $message);
			}else{
				$pushmsg;
			}
		}else{
			return $save;
		}
	}

	/**
	 * 提现申请异步处理成功
	 * @param $data
	 *
	 * @return array
	 */
	public function withdrawSuccess($data){
		$resp = json_decode($data['mer_priv']);
		$unite = $this->getCache('dealType_withdrawSuccess');
		$money = M('WangkaShop')->where('sid='.$resp['sid'])->field('freeze, withdraw_num, withdraw_total')->find();
		$data = array(
			'freeze'        => $money['freeze'] - $data['trans_amt'],
			'withdraw_num'  => $money['withdraw_num'] + 1,
			'withdraw_total'=> $money['withdraw_total'] + $data['trans_amt'],
			'last_changes'  => 'withdrawSuccess',
			'last_unite'    => $unite['id'],
			'last_remark'   => $data['trans_amt'],
		);
		$save = $this->curd(array('type' => 'save', 'model' => M('WangkaShop'), 'where' => 'sid='.$resp['sid'], 'data' => $data));
		if($save['errcode'] == 0){
			$openid = M('WangkaBindView')->where('sid='.$resp['sid'])->limit(1)->getField('boss_openid');
			$message = '您有一笔提现已成功, 提现金额: ￥'.$data['trans_amt'].', 此笔提现扣除手续费: ￥'.$data['fee_amt'].',实际到账金额为: ￥'.$data['real_trans_amt'].'! ';
			$pushmsg = D('Pushmsg')->message('WKSHOP', $openid, $message);
			if($pushmsg['errcode'] == 0){
				return array('errcode' => '0', 'content' => $message);
			}else{
				$pushmsg;
			}
		}else{
			return $save;
		}
	}

	/**
	 * 提现申请异步处理失败
	 * @param $data
	 *
	 * @return array
	 */
	public function withdrawFail($data){
		$resp = json_decode($data['mer_priv']);
		$unite = $this->getCache('dealType_withdrawFail');
		$money = M('WangkaShop')->where('sid='.$resp['sid'])->field('freeze, withdraw_num, withdraw_total')->find();
		$data = array(
			'freeze'        => $money['freeze'] - $data['trans_amt'],
			'withdraw'      => $money['withdraw'] + $data['trans_amt'],
			'last_changes'  => 'withdrawFail',
			'last_unite'    => $unite['id'],
			'last_remark'   => $data['trans_amt'],
		);
		$save = $this->curd(array('type' => 'save', 'model' => M('WangkaShop'), 'where' => 'sid='.$resp['sid'], 'data' => $data));
		if($save['errcode'] == 0){
			$openid = M('WangkaBindView')->where('sid='.$resp['sid'])->limit(1)->getField('boss_openid');
			$message = '您有一笔提现失败啦, 原因是: '.urldecode($data['resp_desc']);
			$pushmsg = D('Pushmsg')->message('WKSHOP', $openid, $message);
			if($pushmsg['errcode'] == 0){
				return array('errcode' => '0', 'content' => $message);
			}else{
				return $pushmsg;
			}
		}else{
			return $save;
		}
	}

	public function balance(){
		Vendor('ChinaPnr');
		$pnr = new ChinaPnr();
		$wx = session('wkshop');
		$post = array(
			'user_cust_id'  => $wx['sideInfo']['user_cust_id'],
			'mer_priv'      => json_encode_plus(array('sid' => $wx['sideInfo']['sid'], 'uid' => $wx['sideInfo']['uid'])),
		);
		return $pnr->balance($post);
	}

	public function getShopInfo($param, $type='openid'){
		switch($type){
			case 'sid':
				$where = 'sid='.$param;
				break;
			case 'openid':
				$where = 'openid="'.$param.'"';
				break;
		}
		return $this->curd(array('type' => 'find', 'model' => M('WangkaBindView'), 'where' => $where));
	}

	public function qrcode2ShopInfo($qrcode){
		return $this->curd(array(
			'type'  => 'find',
			'model' => M('WangkaBindView'),
			'where' => 'md5key="'.$qrcode.'"',
		));;
	}

	public function setShopInfo($param, $sid=null){
		if(is_null($sid)){
			$wx = session('wkshop');
			if(is_null($wx['sideInfo']['sid']))
				return array('errcode' => '30100');
			else
				$sid = $wx['sideInfo']['sid'];
			Vendor('Weixin');
			$weixin = new Weixin('WKSHOP');
			$target = '/Public/Upload/Business';
			if($param['logo']){
				$res = $weixin->get_media($param['logo'], $target);
				if($res['type'] == 'error')
					return $res;
				else
					$param['logo'] = $res['url'];
			}
			if($param['banner']){
				$res = $weixin->get_media($param['banner'], $target);
				if($res['type'] == 'error')
					return $res;
				else
					$param['banner'] = $res['url'];
			}
		}
		$save = D('Public')->curd(array('type' => 'save', 'model' => M('WangkaShop'), 'data' => $param, 'where' => 'sid='.$sid));
		if($save['errcode'] == 0){
			return array('errcode' => '0', 'content' => '更新商铺资料成功!');
		}else{
			return $save;
		}
	}

	public function getShopOrder($sid){
		if(!is_null($sid)){
			$list = $this->curd(array(
				'model' => M('WangkaOrder'),
				'where' => 'sid='.$sid,
				'type'  => 'select',
			    'order' => 'pay_dateline DESC',
			));
			if($list['errcode'] == '0'){
				foreach($list['data'] AS $val){
					if($val['delete_flag'] == 0){
						if($val['status_flag'] == 1)
							$status = '已确认';
						else
							$status = '待确认';
					}else{
						$status = '已取消';
					}
					$data[] = array_merge($val, array('status'    => $status));
				}
				$list['data'] = $data;
			}
			return $list;
		}else{
			return array('errcode' => '30100');
		}
	}

	public function checkBindShop($openid){
		$view = $this->getShopInfo($openid);
		if(is_null($view['sid']))
			return array('errcode' => '30100');
		else
			return array('errcode' => '0', 'data' => $view);
	}

	public function getShopList($cid){
		if($cid == 0){
			$where = 'cid != 0';
		}else{
			$catid[] = $cid;
			foreach(D('Business')->getCategory($cid) AS $val){
				$catid[] = $val['id'];
			}
			$where['cid'] = array('in', $catid);
		}
		foreach(M('WangkaShop')->where($where)->select() AS $val){
			$return[] = array_merge($val, array(
				'logo_img'      => array(
					'src'   => $val['logo'],
					'class' => is_null($val['logo'])?'lowersrc':'',
					'attr'  => is_null($val['logo'])?'商铺未上传Logo':'',
				),
				'banner_img'    => array(
					'src'   => $val['banner'],
					'class' => is_null($val['banner'])?'lowersrc':'',
					'attr'  => is_null($val['banner'])?'商铺未上传banner':'',
				),
				'address'       => $val['province'].$val['city'].$val['dist'].$val['community'].$val['suite'],
				'tel'           => is_null($val['telephone'])?M('WangkaUser')->where('uid='.$val['uid'])->getField('mobile'):$val['telephone'],
				'url'           => U('Business/shopInfo', array('sid' => $val['sid'])),
			));
		}
		return array('errcode' => '0', 'data' =>$return);
	}

	public function getLog($uid, $sid){
		$data = M('WangkaLog')->where('uid='.$uid.' AND sid='.$sid)->select();
		foreach($data AS $key => $val){
			$data[$key]['datetime'] = date('Y-m-d H:i:s', $val['dateline']);
		}
		return array('errcode' => '0', 'data' =>$data);
	}

	/**
	 * 获取店铺员工数据列表, 如果角色不是老板或没有创建绑定过店铺则返回错误信息
	 * @return array
	 */
	public function getPresonList($info){
		$sess = $this->checkBossRole($info['role']);
		if($sess['type'] == 'success')
			return array('errcode' => '0', 'data' => M('WangkaBindView')->where('sid='.$info['sid'])->select());
		else
			return $sess;
	}

	/**
	 * 辞退员工操作, 如果角色不是老板或没有创建绑定过店铺则返回错误信息
	 * @param $uid  需要辞退员工的uid
	 * @param $info 需要辞退员工的店铺信息
	 *
	 * @return array    返回操作数据
	 */
	public function removePreson($uid, $info){
		$sess = $this->checkBossRole($info['role']);
		if($sess['type'] == 'success'){
			$del = D('Public')->curd(array('type' => 'delete', 'model' => M('WangkaShop'), 'where' => array('sid' => $info['sid'], 'uid' => $uid)));
			if($del['errcode'] == 0)
				return array('errcode' => '0', 'content' => '辞退员工操作成功!');
			else
				return $del;
		}else{
			return $sess;
		}
	}

	public function createOrder($id, $uid){
		$boss_uid = M('WangkaBindView')->where('uid='.$uid)->getField('boss_uid');
		$orderTable = M('WangkaOrder');
		$order = M('PayWangkaView','t_','mysql://weixin_user:weixin_HYCT0871@120.25.67.227/stages')->where('id="'.$id.'"')->find();
		if(!is_null($order) && is_array($order)){
			$data = array(
				'uuid'          => $id,
				'sid'           => $order['shop_id'],
				'uid'           => $uid,
				'boss_uid'      => $boss_uid,
				'real_money'    => $order['real_money'],
				'sum_money'     => $order['sum_money'],
				'ticket_money'  => $order['ticket_money'],
				'status_flag'   => $order['statusflag'],
				'delete_flag'   => $order['delete_flag'],
				'pay_dateline'  => strtotime($order['pay_time']),
				'customer_name' => $order['name'],
				'customer_tel'  => $order['telephone'],
			);
			$add = D('Public')->curd(array('type' => 'add', 'model' => $orderTable, 'data' => $data));
			if($add['errcode'] == 0)
				return array('errcode' => '0', 'data' => $data);
			else
				return $add;
		}else{
			return array('errcode' => '30111');
		}
	}

	public function orderStatus($uuid, $status=0){
		$state = ($status == 0)?2:$status;
		if(M('WangkaOrder')->where('uuid="'.$uuid.'"')->setField('status_flag', $state)){
			$url = 'http://admin.mywoka.com/stages/scanCodeCilentController/scanPayMoneyWangkaCallBack.action';
			$data = array('app_primary' => $uuid, 'confirmation' => $status);
			return $this->curlData($url, $data, 'POST');
		}
	}

	public function getBankData($uid){
		$user = M('WangkaBindView')->where('uid='.$uid)->field('sid, isbind, is_bind_bank, user_cust_id, role, user_name, cert_id')->find();
		if($user['is_bind_bank'] == 1){
			Vendor('ChinaPnr');
			$pnr = new ChinaPnr();
			$bank = M('WangkaBank')->where('sid='.$user['sid'])->find();
			$balance = $pnr->balance(array('user_cust_id' => $user['user_cust_id']));
		}else{
			$bank = array(
				'bank_id'   => null,
				'bank_name' => null,
				'bank_code' => null,
			);
			$balance['data']= array('cash_balance' => 0);
		}
		$unite = M('WangkaUnite')->where('gid=1 AND code IS NOT NULL')->select();
		$prov = M('District')->where('upid=0 AND prov IS NOT NULL')->select();
		return array('errcode' => 0, 'data' => array(
			'isbind'        => $user['isbind'],
			'is_bind_bank'  => $user['is_bind_bank'],
			'role'          => $user['role'],
			'bank_id'       => $bank['bank_id'],
			'bank_name'     => $bank['bank_name'],
			'bank_code'     => $bank['bank_code'],
			'user_name'     => $user['user_name'],
			'cert_id'       => $user['cert_id'],
			'money'         => $balance['data']['cash_balance'],
			'bank'          => $unite,
			'prov'          => $prov,
		));
	}

	public function getCashList($sid){
		$return = $this->curd(array(
			'model' => M('PayWangkaView','t_','mysql://weixin_user:weixin_HYCT0871@120.25.67.227/stages'),
			'where' => 'shop_id='.$sid,
			'type'  => 'select',
		));
		return $return;
	}

	public function getAreaData($did){
		return array('errcode' => 0, 'data' => M('District')->where('prov IS NOT NULL AND upid = '.$did)->select());
	}

	private function checkBossRole($role){
		if($role == 'boss')
			return array('errcode' => '0');
		elseif(is_null($role))
			return array('errcode' => '30100');
		else
			return array('errcode' => '30110');
	}
}